<?php
declare(strict_types=1);
/**
 * 南方国通API中心
 */
namespace Service\VenderClient\WayBillExpressCompanyApi;
use Service\Code\Normal;
use Service\BaseService;
use Service\ExtraService\TaskWorker;
use Service\HttpServer\Http;
use Service\ExtraService\Guid;
use Service\ExtraService\ArrayToXML;
class SCGTCompanyApiClient extends BaseService
{
    protected $config;
    const API_URL = 'https://izop.zt-express.com/oms/api';
    public function __construct( array $apiBody = [] )
    {
        $this->config = $apiBody;
    }
    public function logisticDeclare( array $declareInfo = []){   
        $receiveInfo = $declareInfo['receiveInfo'];
        $senderInfo  = $declareInfo['senderInfo'];
        $orderGoods  = $declareInfo['orderGoods'];
        $order       = $declareInfo['order'];
        $goods       = $declareInfo['goods'];
        $e_company   = $declareInfo['e_company'];
        if (empty($order['express_num'])) {
            $mailInfo = $this->getLogisticOrderCode($declareInfo);            
            if ($mailInfo['code'] != Normal::SUC) {
                return $mailInfo;
            }
            $logisticsNo = $mailInfo['data']['waybillNo'];
        } else {
            $logisticsNo = $order['express_num']; //物流企业运单号
        }
        $responseData=[
                'waybillNo'          => $mailInfo['data']['waybillNo']??'',//运单号
                'bigWord'            => $mailInfo['data']['preSortResult']['sourceTabletrolleyCode']??'',//大字/三段码
                'packagePlace'       => $mailInfo['data']['preSortResult']['collectionAddress']??'',//集包地
                'originData'         => $mailInfo['data']['preSortResult']?json_encode($mailInfo['data']['preSortResult'],JSON_UNESCAPED_UNICODE):'',//返回的原始数据result字符串,
            ];
        $declaredata=$declareInfo;
        $declaredata['logisticsNo']=$logisticsNo;
        $declareResponse= $this->getLogisticDeclare($declaredata);
        if (isset($declareResponse['code']) && $declareResponse['code'] == Normal::SUC) {
            //self::addLocalStorageFileRecordByPath($file_path, $file, json_encode($result));
            return Normal::returnCode(Normal::SUC, "申报运单号成功", $responseData);
        }
        $message = $declareResponse['message'] ?? '申报运单号失败';
        return Normal::returnCode(Normal::FAIL, $message,$responseData);
    }
    public function getLogisticOrderCode(array $logisticsGeneralInfo)
    {
        $receiveInfo = $logisticsGeneralInfo['receiveInfo'];
        $senderInfo  = $logisticsGeneralInfo['senderInfo'];
        $orderGoods  = $logisticsGeneralInfo['orderGoods'];
        $order       = $logisticsGeneralInfo['order'];
        $goods       = $logisticsGeneralInfo['goods'];
        $e_company   = $logisticsGeneralInfo['e_company'];
        $customerCode = $this->config['customerCode'];
        $appKey = $this->config['appKey'];
        $basic = base64_encode($customerCode.':'.$appKey);
        $header = [
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: Basic '.$basic
        ];
        $data = [
            'companyCode'           => $customerCode,
            'CompanyName'           => $this->config['CompanyName'],
            'orderId'               => $order['sn'],
            'senderName'            => $senderInfo['SenderName'],
            'senderAddress'         => $senderInfo['SenderProvince'].$senderInfo['SenderCity'].$senderInfo['SenderCountry'].$senderInfo['SenderAddress'],
            'senderTel'             => $senderInfo['SenderPhone'],
            'senderMobile'          => $senderInfo['SenderPhone'],
            'receiveName'           => $receiveInfo['ReceiverName'],
            'receiveAddress'        => $receiveInfo['ReceiverProvince'].$receiveInfo['ReceiverCity'].$receiveInfo['ReceiverCountry'].$receiveInfo['ReceiverAddress'],
            'receiveTel'            => $receiveInfo['ReceiverPhone'],
            'receiveMobile'         => $receiveInfo['ReceiverPhone'],
            'packageCount'          => '1',
            'weight'                => $this->getWeight($logisticsGeneralInfo),
            'vloumn'                => '10'
        ];
        $result = $this->execute('SCGTGetMailNo',$this->config['getWayBillCodeURL'],['jsonString'=>json_encode($data,JSON_UNESCAPED_UNICODE)],$header);
        
        //$result   = json_decode($response,true);
        if( isset($result['jingdong_ldop_waybill_receive_responce']) && 
            isset($result['jingdong_ldop_waybill_receive_responce']['receiveorderinfo_result']) &&
            isset($result['jingdong_ldop_waybill_receive_responce']['receiveorderinfo_result']['resultCode']) &&
            $result['jingdong_ldop_waybill_receive_responce']['receiveorderinfo_result']['resultCode'] == '100'
         )
        {

            $receiveorderinfo_result = $result['jingdong_ldop_waybill_receive_responce']['receiveorderinfo_result'];
            return Normal::returnCode(Normal::SUC, "取号成功", [
                'waybillNo'     => $receiveorderinfo_result['deliveryId'],//运单号
                'preSortResult' => $receiveorderinfo_result['preSortResult'],//取号信息
            ]);
        }
        
        $resultMessage = $result['jingdong_ldop_waybill_receive_responce']['receiveorderinfo_result']['resultMessage'] ??"";
        return Normal::returnCode(Normal::FAIL,"京东取消取号失败[{$resultMessage}]",$result);
    }
    
    public function getLogisticDeclare(array $logisticsGeneralInfo) {
        $receiveInfo = $logisticsGeneralInfo['receiveInfo'];
        $senderInfo  = $logisticsGeneralInfo['senderInfo'];
        $orderGoods  = $logisticsGeneralInfo['orderGoods'];
        $order       = $logisticsGeneralInfo['order'];
        $goods       = $logisticsGeneralInfo['goods'];
        $e_company   = $logisticsGeneralInfo['e_company'];
        $logisticshead=[
            'ceb:LogisticsHead'=>[
                'ceb:guid'=> Guid::getGuidOnlyValue(),//企业系统生成36位唯一序号（英文字母大写）。
                'ceb:appType'=>1,//企业报送类型。1-新增 2-变更 3删除
                'ceb:appTime'=>date('YmdHis'),    //企业报送时间
                'ceb:appStatus'=>2,//业务状态:1-暂存,2-申报,默认为 2。
                'ceb:logisticsCode'=> $this->config['logisticCustomCode'],//物流企业的海关注册登记编号。
                'ceb:logisticsName'=> $this->config['logisticCustomName'],//物流企业在海关注册登记的名称。
                'ceb:logisticsNo'=>$logisticsGeneralInfo['logisticsNo'],//物流企业的运单包裹面单号。同一物流企业的运单编号在6个月内不重复。运单编号长度不能超过60 位。
                'ceb:billNo'=>'',//直购进口为海运提单、空运总单或汽车载货清单
                'ceb:freight'=>'0',//商品运输费用，无则填“0”
                'ceb:insuredFee'=>'0',//商品保险费用，无则填“0”
                'ceb:currency'=>'142',//限定为人民币，填写“142”
                'ceb:weight'=> $this->getWeight($logisticsGeneralInfo),//单位为千克。
                'ceb:packNo'=>'1',//单个运单下包裹数，限定为“1”。
                'ceb:goodsInfo'=>'',//配送的商品信息，包括商品名称、数量等。
                'ceb:consignee'=>$receiveInfo['ReceiverName'],//收货人姓名。
                'ceb:orderNo'=>$order['sn'],//交易平台的订单编号，同一交易平台的订单编号应唯一。订单编号长度不能超过60位。
                'ceb:consigneeAddress'=>$receiveInfo['ReceiverProvince'].$receiveInfo['ReceiverCity'].$receiveInfo['ReceiverCountry'].$receiveInfo['ReceiverAddress'],//收货地址。
                'ceb:consigneeTelephone'=>$receiveInfo['ReceiverPhone'],//收货人电话号码。
                'ceb:note'=>''//备注
            ]
        ];
        $res = [];  
        $res['ceb:CEB511Message'] = [  
            'guid'         =>      Guid::getGuidOnlyValue(),  
            'version'      =>      '1.0',  
            'xmlns:ceb'    =>      'http://www.chinaport.gov.cn/ceb',  
            'xmlns:xsi'    =>      'http://www.w3.org/2001/XMLSchema-instance', 
            'ceb:Logistics'     =>$logisticshead,
        ]; 
        $xml= ArrayToXML::toXml($res);    
        $url=$this->config['wayBillDeclareURL'];
        $urldata = [
            'clientid'      => $this->config['clientid'],
            'key'           => $this->config['key'],
            'messageType'   => 'CEB511Message',
        ];
        $url = $url."?".http_build_query($urldata);
        $response = $this->execute('SCGTDeclare',$url,base64_encode($xml),['Content-Type: application/xml']);
        if(isset($response['result'])&&$response['result']==true&&isset($response['childList'])&&$response['childList'][0]['result']==true){
            return Normal::returnCode(Normal::SUC, "申报成功", $response);
        }else{
            $message=$response['childList'][0]['message']??$response['description'];
            return Normal::returnCode(Normal::FAIL, $message, $response);
        }
    }


    protected function getWeight( array $logisticsGeneralInfo)
    {
        $goods = $logisticsGeneralInfo['goods'];
        $orderGoods = $logisticsGeneralInfo['orderGoods'];
        $weight=0;
        $intlOrderItemList = [];
        foreach ($orderGoods as $item) {
            $weight= bcadd((string)$weight, (string)$goods[$item['goods_id']]['weight']);
        }
        $weight=round($weight/1000, 3);
        return (string)$weight;
    }
    
     /**
     * 推送接口
     * @param string $method
     * @param array $body
     */
    public function execute(string $method ,string $url, $body,array $header)
    {
        $parameter = [
            [
                'tag'       => 'scgt_order_'.$method,
                'url'       => $url,
                'data'      => $body,
                'method'    => 'post',
                'format'    => 'other',
                'header'    => $header
            ],
        ];
        $resTask    = TaskWorker::instance()->addTask($parameter);
        $resTask    = current($resTask);
        $response   = @json_decode($resTask['response']['result'],true);        
        return $response;
    }
}
